/*
 * @Author: 晴鸢. 3013433857@qq.com
 * @Date: 2025-10-31 09:55:59
 * @LastEditors: 晴鸢. 3013433857@qq.com
 * @LastEditTime: 2025-11-03 23:29:27
 * @FilePath: /Learn/WebCalculator/ClientCal.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include<string>
#include<time.h>
#include<assert.h>
#include<unistd.h>
#include"Socket.hpp"
#include"Protocol.hpp"
void Usage(const std::string &proc)
{
    std::cout<<"Usage:"<<proc<<"serverip serverport\n"<<std::endl;
}
//./clientcal ip port
int main(int argc,char*argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip=argv[1];
    uint16_t serverport=std::stoi(argv[2]);

    Sock sockfd;
    sockfd.Socket();
    bool r=sockfd.Connect(serverip,serverport);
    if(!r)  return 1;

    srand(time(nullptr));
    int cnt=1;
    const std::string opers="+-*/%=&^~";//操作码
    std::string inbuffer_stream;
    while(cnt<=10)
    {
        std::cout<<"===========第"<<cnt<<"次测试=========="<<std::endl;
        int x=rand()%100+1;
        usleep(123);
        int y=rand()%100;
        usleep(321);
        char oper=opers[rand()%opers.size()];
        Request req(x,y,oper);
        req.DebugPrint();
        //序列化
        std::string package;
        req.Serialize(&package);
        package=Encode(package);
        std::cout<<"最新请求：\n"<<package;
        write(sockfd.getfd(),package.c_str(),package.size());
        /*
        std::cout<<"最新请求：\n"<<package;
        write(sockfd.getfd(),package.c_str(),sizeof(package));
        std::cout<<"最新请求：\n"<<package;
        write(sockfd.getfd(),package.c_str(),sizeof(package));
        std::cout<<"最新请求：\n"<<package;
        write(sockfd.getfd(),package.c_str(),sizeof(package));
        */
        char buffer[128];
        ssize_t n=read(sockfd.getfd(),buffer,sizeof(buffer));
        if(n>0)
        {
            buffer[n]=0;
            inbuffer_stream+=buffer;//len\n result code\n
            std::cout<<inbuffer_stream<<std::endl; 
            std::string content;
            bool r=Decode(inbuffer_stream,&content);
            assert(r);
            
            Response resp;
            r=resp.Deserialize(content);
            assert(r);

            resp.DebugPrint();
        }
        std::cout<<"========================="<<std::endl;
        sleep(1);
        cnt++;
    }
    sockfd.Close();
    return 0;
}